var jsonObject = {};
var personIDs = new Array();
var personProfiles = new Array();
var selectedIndex = -1;
var personProfile = {};

var healthMagicBoxDataSet = {
	openDatabase : function() {
					var database = window.openDatabase("healthMagicBoxLocalDB", "0.1", "HealthMagicBox mobileDB", 2 * 1024 * 1024);
					console.log("openDatabase:" + database);
					return database;
					},
	createUserTable : function(db) {
		if(db == null) {
			console.log("User Table : database is empty");
			return false;
		}else {
			db.transaction(function(tx) {
				tx.executeSql("CREATE TABLE IF NOT EXISTS Users(\
				id integer primary key autoincrement ,\
				username varchar(20),\
				password varchar(50),\
				clearp varchar(20),\
				personID varchar(15),\
				role varchar(10), \
				email varchar(30),\
				phonenum varchar(15), \
				inviteID int NOT NULL,\
				thirdlogintype varchar(15),\
				thirdloginID varchar(15),\
				created datetime,\
				modified datetime,\
				active int)",
				[],
				function(tx, result){console.log("users table is created.");},
				function(tx, error) {console.log("users table created failed" + error.message);});
			});
		}
	},
	createPersonProfileTable: function(db) {
		if(db == null) {
			console.log("PersonProfileTable: database is empty");
			return false;
		}else {
			db.transaction(function(tx) {
				tx.executeSql("CREATE TABLE IF NOT EXISTS PersonProfile (\
				id integer primary key autoincrement ,\
				personID varchar(50),\
				name varchar(50), \
				age int,\
				allergy varchar(50),\
				height double,	\
				weight double,\
				imageFileName varchar(50),\
				qq varchar(50),\
				sex varchar(50),\
				manualInput int,\
				sinaWeiBo varchar(50),\
				created datetime,\
				modified datetime,\
				active int,\
				life varchar(30),\
				eat varchar(30),\
				issues varchar(30),\
				birthDay int,\
				birthMonth int,\
				birthYear int,\
				invitedCode varchar(10),\
				sharelist varchar(100))",
				[],
				function(tx, result){console.log("PersonProfiles table is created.");},
				function(tx, error) {console.log("PersonProfiles table created failed" + error.message);});
			});
		}
	},

	createUserToPersonTable: function(db) {
		if(db == null) {
			console.log("UserToPerson: database is empty");
			return false;
		}else {
			db.transaction(function(tx) {
				tx.executeSql("CREATE TABLE IF NOT EXISTS UserToPerson (\
				ID integer,\
				personID varchar(15),\
				userName varchar(30), \
				retitle varchar(10), \
				modified datetime)",
				[],
				function(tx, result){console.log("UserToPerson table is created.");},
				function(tx, error) {console.log("UsetroPerson table created failed" + error.message);});
			});
		}
	}
};

function ajaxPost(postURL, para, callback) {
	var url = postURL;
	console.log("ajaxPost : " + postURL + para);
	$.post(url, para, callback);
};

function downloadPersonProfile(personID) {
    var postURL = "http://kangbox.cn/cakephp/mobileUsersAdapter/downloadpersonprofile";

    var callback = function(jsonResponse) {
        console.log(jsonResponse);
        if (jsonResponse.length == 0) {
            //put a placeholder
            console.log("json_response string is empty.");
        } else {
            var db = healthMagicBoxDataSet.openDatabase();

            if (jsonResponse.search("NO MORE") != -1) {
                return;
            }

            jsonObject = JSON.parse(jsonResponse);
            personProfile = jsonObject;

            //save data into the database
            db.transaction(function(tx) {
            	console.log("testing testing " + jsonResponse);
                for (var i = 0; i < jsonObject.length; i++) {
                    var data = jsonObject[i].PersonProfile;
                    tx.executeSql(
                        "INSERT INTO PersonProfile " + "(personID, name, age, allergy, height, weight, imageFileName, qq, \
								sex, manualInput, sinaWeiBo, created, modified, active, life,\
								eat,issues, birthDay, birthMonth ,birthYear, invitedCode, sharelist) \
						        values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [data.personID, data.name, parseInt(data.age), data.allergy, parseFloat(data.heigth), parseFloat(data.weigth), data.imageFileName,
                            data.qq, data.sex, data.manualinput, data.sinaWeibo, data.created, data.modified, parseInt(data.active),
                            data.life, data.eat, data.issues, parseInt(data.birthDay), parseInt(data.birthMonth), data.birthYear, parseInt(data.invitedCode), data.sharelist
                        ],
                        function(tx, result) {
                            console.log("insert data successfully" + result);
                            showPersonProfile();
                        },
                        function(tx, result) {
                            console.log("insert data failed " + result);
                        });
                }
            });
        }
    };

    var para = {
        jsonstring: JSON.stringify({
            personID: personID
        })
    };
    ajaxPost(postURL, para, callback);

};


function downloadUserToPersonData() {
	var postURL = "http://kangbox.cn/cakephp/mobileUsersAdapter/mobileusertopersonsdown";

	var callback = function(jsonResponse) {
	    if (jsonResponse.length == 0) {
	        //put a placeholder
	        console.log("json_response string is empty.");
	    } else {
	        if (jsonResponse.search("NO MORE") != -1) {
	            return;
	        }
	        jsonObject = JSON.parse(jsonResponse);

	        //save data into the database
	        var db = healthMagicBoxDataSet.openDatabase();
	        db.transaction(function(tx, jsonResponse) {
	        
	            for (var i = 0; i < jsonObject.length; i++) {
	                var data = jsonObject[i].UserToPerson;
	              
	                tx.executeSql(
	                    "INSERT INTO UserToPerson " + "(ID, personID, userName, retitle, modified) values(?, ?, ?, ?, ?)", [parseInt(data.id), data.personID, data.username, data.retitle, data.modified],
	                    function(tx, result) {
	                        console.log("insert data successfully" + result);
	                    },
	                    function(tx, result) {
	                        console.log("insert usertoperson : insert data failed " + result);
	                    });
	                  getPersonProfile(data.personID);
	            }
	        });
	    }
	};
	var para = {
	    jsonstring: JSON.stringify({
	        username: localStorage.getItem("XPP_USERNAME")
	    })
	};
	ajaxPost(postURL, para, callback);
}

var userToPersonData = {};

function getUserToPersonDataSuccessCallback(tx, result) {
	//1. if find then to see whether we have personProfile data locally.
	//2. if not, try to down the data from internet and store them. 
	/*console.log("get userToPersonData from local with succeed");*/

	var obj = result;
	personID = obj.personID;
	$.ui.popup("fuck personID = " + personID + "window.personID= " + window.personID);
};

function showPersonProfile() {
	personProfiles.push(personProfile);
   var item = '<li><a href="#healthInputDataList"><img src="images/img2.jpg" />' + personProfile.name + '</a></li>';
   $("#personsImageList").append($.create(item));
   $("li").bind("click", function(){
   		selectedIndex = $(this).index();
   });
};


function getPersonProfile(personID) {
    var db = healthMagicBoxDataSet.openDatabase();
    db.transaction(function(tx) {
        tx.executeSql(
            "SELECT * FROM PersonProfile WHERE personID =?", [personID],
            function(tx, result) {
                console.log("get data successfully" + result);
                if (result.rows.length != 0) {
                    personProfile = result.rows.item(0);
                    showPersonProfile();
                } else {
                    console.log("getPersonProfile : no item was selected");
                    downloadPersonProfile(personID);
                }
            },
            function(tx, result) {
                console.log("get data failed " + result);
            });
    });
};


function getUserToPersonData() {
	var db = healthMagicBoxDataSet.openDatabase();
	db.transaction(function(tx) {
        tx.executeSql(
            "SELECT personID FROM UserToPerson WHERE userName = ?", [localStorage.getItem("XPP_USERNAME")],
            //"SELECT * FROM UserToPerson", [],
            function(tx, result) {
                console.log("get data successfully " + result.rows.length);
                if(result.rows.length != 0){
                	for(var i = 0; i < result.rows.length; i ++) {
                		personIDs[i] = result.rows.item(i).personID;
                		getPersonProfile(result.rows.item(i).personID);
                	}
                } else {
                	downloadUserToPersonData();
                }
            },
            function(tx, result) {
                console.log("get data failed " + result);
                
            });
	});
}

